/**
 * Created by songjuxi on 2017/3/29.
 */
import React, {Component} from 'react';
import Loadable from 'react-loadable';
import PropTypes from 'prop-types';
import { Table, message } from 'jdcloudui';
import FuncPermission  from 'jdcloudecc/components/FuncPermission/FuncPermission';
import RiskUser from 'jdcloudecc/components/RiskUser/RiskUser';
import style from './style/style.less'
import './style/style.css';

function Loading(props) {
  if (props.error) {
    return <div>Error!</div>;
  } else if (props.pastDelay) {
    return <div>Loading...</div>;
  } else {
    return null;
  }
}

const PAGE_SIZE=10
export default class InvoiceOperatingList extends Component{
  constructor(props){
    super(props);
    this.state = {
      components: null
    };
  }
  loadInstance = () => {
    var {components = {}} = this.props.components||{};
    var instances = {};
    Object.keys(components).map((hook)=>{
      components[hook].map((value)=>{
        const componentName = value["name"];
        var Ins = Loadable({
          loader: () => import(`../${componentName}/${componentName}`).then(object => object.default),
          loading: Loading,
          delay: 10,
          render(loaded) {
            let Component = loaded;
            let props = value["config"],key = "key_"+value["id"];
            return <Component {...props} genKey={key} />;
          }
        });
        instances[hook] = instances[hook] || [];
        instances[hook].push(Ins)
      });
    });

    return instances;
  }
  showModal(){
     this.props.showModal(true);
  }
  getLinkData(e){
    let tar=e.target
    const linkdata={
      linkMan:tar.getAttribute('data-linkman'),
      linkAddress:tar.getAttribute('data-linkaddress'),
      linkPhone:tar.getAttribute('data-linkphone'),
      id:tar.getAttribute('data-id')
    }
    this.props.getLinkData(linkdata);
  }
  componentDidMount() {
    let initalValues={pageSize:PAGE_SIZE,pageNum:1}
    if(this.props.status==0){
      initalValues.status=0
    }
    this.props.saveFormData(initalValues)
    this.props.buyerBillSearch(initalValues)
      .then(
        (result)=>{console.log('成功')},
        (err)=>{console.log('失败')}
      );
    //获取权限数据
    this.props.getPlatformFuncPermission().then((result) => {
      let permissionData = result && result.data || {};
      if(permissionData && permissionData.code != 0){
        message.warning("菜单权限获取失败！");
      }
    });

    // 动态加载 modal组件
    this.props.load().then(() => {
      this.setState({
        components: this.loadInstance()
      });
    });
  }
  createDate(){
    if(this.props.InvoiceOperatingView.data){
      if(this.props.InvoiceOperatingView.data.code==0){
        const data=this.props.InvoiceOperatingView.data.data||{}
        return data.result
      }
      return[]
    }
    return []
  }
  onPageChange(pageNum,pageSize){
    let searchdata = this.props.InvoiceOperatingView.searchdata || {};
    searchdata.pageNum=pageNum
    searchdata.pageSize=pageSize
    this.props.buyerBillSearch(searchdata).then(
      (reslut)=>{
        console.log('成功')},
      (err)=>{console.log(err)}
    )

  }
  createPagination(){
    let current=this.props.InvoiceOperatingView.data && this.props.InvoiceOperatingView.data.data &&this.props.InvoiceOperatingView.data.data.pageNum;
    let total=this.props.InvoiceOperatingView.data && this.props.InvoiceOperatingView.data.data && this.props.InvoiceOperatingView.data.data.totalCount;
    return {
      current:current,
      total:total,
      showQuickJumper:true,
      pageSize:PAGE_SIZE,
      onChange:this.onPageChange.bind(this)

    };
  }
  render(){
    const orderStatusCheck={
      5:'待付定金',
      10:'待审批',
      11:'审批驳回',
      15:'已付款',
      20:'待发货',
      30:'部分发货',
      40:'全部发货',
      50:'订单完成',
      60:'待评价',
      70:'已评价',
      80:'已取消',
    }
    const stausColor={
      5:'text-warning',
      10:'text-warning',
      11:'text-error',
      15:'text-success',
      20:'text-warning',
      30:'text-warning',
      40:'text-success',
      50:'text-success',
      60:'text-warning',
      70:'text-success',
      80:'text-disabled'
    }
    const invoiceStatusColor={
      1:'text-success',
      0:'text-warning'
    }

    let data=this.props.InvoiceOperatingView.data||{}
    data=data.data||{}
    const {totalPageCount,firstPage,lastPage,nextPage}=data
    const columns = [{
      title: <span className="text-666">订单编号</span>,
      dataIndex: 'orderNo',
      className:'text-333',
      render:(orderNo,b,index)=><div key={`orderNo${index}`} >{orderNo}</div>
    }, {
      title: <span className="text-666">下单时间</span>,
      dataIndex: 'orderTime',
      className:'text-333',
      render:(orderTime,b,index)=><div className={style.rowTime} key={`orderTime${index}`}>{orderTime}</div>
    }, {
      title: <span className="text-666">订单状态</span>,
      dataIndex: 'orderStatusView',
      className:'text-333',
      render:(orderStatusView,record,index)=><div className={stausColor[record.orderStatus]} key={`orderStatus${index}`}>{orderStatusView}</div>

    },{
      title: <span className="text-666">订单金额</span>,
      dataIndex: 'paymentPrice',
      className:'text-333',
      render:(paymentPrice,b,index)=><div key={`paymentPrice${index}`}>{'￥'+parseFloat(paymentPrice).toFixed(2)}</div>
    },{
      title: <span className="text-666">采购商名称</span>,
      dataIndex: 'purchaseName',
      className:'text-333',
      render:(purchaseName,record,index)=><RiskUser riskState={record.riskUserType}>
        <span key={`purchaseName${index}`}>{purchaseName}</span>
      </RiskUser>

    },{
      title: <span className="text-666">开票时间</span>,
      dataIndex: 'invoiceDate',
      className:'text-333',
      render:(invoiceDate,b,index)=><div className={style.rowTime} key={`invoiceDate${index}`}>{invoiceDate}</div>
    },{
      title: <span className="text-666">发票代码</span>,
      dataIndex: 'invoiceCode',
      className:'text-333',
      render:(invoiceCode,b,index)=><div key={`invoiceCode${index}`}>{invoiceCode}</div>
    },{
      title: <span className="text-666">发票号码</span>,
      dataIndex: 'invoiceNum',
      className:'text-333',
      render:(invoiceNum,b,index)=><div key={`invoiceNum${index}`}>{invoiceNum}</div>
    },{
      title: <span className="text-666">发票照片</span>,
      dataIndex: 'invoiceImgSrcName',
      className:'text-333',
      render:(invoiceImgSrcName,record,index)=><a href={record.invoiceImgSrc} target="_blank" key={`invoiceImgSrc${index}`}>{invoiceImgSrcName}</a>
    },{
      title: <span className="text-666">物流信息</span>,
      dataIndex: 'logisticsCompany',
      className:'text-333',
      render:(logisticsCompany,record,index)=>(<div>
        <div key={`logisticsCompany${index}`}>{record.status==1?logisticsCompany:null}</div>
        <div key={`logisticsNo${index}`}> {record.status==1?record.logisticsNo:null}</div>
      </div>)
    },{
      title: <span className="text-666">开票状态</span>,
      dataIndex: 'status',
      className:'text-333',
      render:(status,record,index)=><div className={invoiceStatusColor[status]} key={'status'+record.id}>{record.invoiceStatusView}</div>
    },{
      title: <span className="text-666">操作</span>,
      dataIndex: 'id',
      render: (orderNo,record,index)=>{
        const {orderStatus,status}=record
        //待付款10，待审批5，待付定金11，审批驳回6，已取消80，
        //待付款、待付定金可开
        //
        const noSHow=[5,80]
        return (<div>
         <a
                key={`invoice${index}`}
                className="mr5"
                onClick={(e)=>{this.showModal();this.getLinkData(e)}}
                data-linkman={record.contactPerson}
                data-linkaddress={(record.provinceName||'')+(record.cityName||'')+(record.countryName||'')+record.fullAddress}
                data-linkphone={record.contactPhone}
                data-id={record.id}
                href="javascript:void(0)">确认开票</a>
          <a
            key={`detail${index}`}
            href={`/order-operating-view/order/order-detail/?orderNo=${record.orderNo}`}>查看订单详情</a>
        </div>)
      }
    }];

    //菜单权限数据处理
    let permissionData = this.props.funcPermissions.data;
    if(permissionData && permissionData.code == 0){
      this.codesResponse = permissionData.data;
      this.codes = this.codesResponse && this.codesResponse.join(",");
    }
    return <div >
      <div className="ui-tbl bb1">
        <Table
          columns={columns}
          dataSource={this.createDate()}
          pagination={this.createPagination()}
          loading={this.props.InvoiceOperatingView.listLoading}
        />
        {
            (this.state.components && this.state.components.HOOK_BuyerBillOperate||[]).map((Component,i)=>{
              return <Component key={i} />
            })
        }
      </div>
    </div>
  }
}
